package ctrl

import (
	"data"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gansidui/geohash"
	"log"
)

const (
	REQUEST_DATA  = "data"
	JSON          = "json"
	MAX_LATITUDE  = 90
	MAX_LONGITUDE = 180
)

type NearbyCtrl struct {
	beego.Controller
}

func (this *NearbyCtrl) Post() {
	log.Print("NearbyCtrl->Post")
	strData := this.GetString(REQUEST_DATA, "")
	log.Print("NearbyCtrl->data\t", strData)
	this.Data[JSON] = this.doLogic(strData)
	this.ServeJson()
}
func (this *NearbyCtrl) doLogic(str string) *data.Result {
	hs := new(data.Hotspot)
	err := json.Unmarshal([]byte(str), hs)
	if err != nil {
		return data.ErrorResult("参数错误!")
	}
	if hs.Latitude > MAX_LATITUDE || hs.Longitude > MAX_LONGITUDE {
		return data.ErrorResult("参数错误!")
	}
	hash, _ := geohash.Encode(hs.Latitude, hs.Longitude, 6)
	o := orm.NewOrm()
	var setter []*data.Hotspot
	l, err := o.QueryTable(hs).Filter("geohash__startswith", hash).All(&setter)
	if err != nil {
		return data.ErrorResult("查询失败!")
	}
	log.Print("NearbyCtrl->doLogic->count:\t", l)
	result := data.SuccessResult("查询成功!")
	result.Data = setter[0:l]
	return result
}
